<template>
  <XenPageLayout
    title="自由排班"
    title-align="left"
    navbar-bg-color="#667eea"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    :contentStyle="'background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 16px; min-height: 100vh;'"
  >
    <!-- 日历视图 -->
    <CalendarView
      :scheduleData="scheduleRecords"
      @monthChange="handleMonthChange"
      @dayClick="handleDayClick"
    />

    <!-- 详情弹窗 -->
    <uni-popup ref="detailPopup" type="bottom" :safe-area="false">
      <view class="detail-popup">
        <view class="popup-header">
          <view class="popup-title">排班详情</view>
          <view class="popup-close" @click="closeDetailPopup">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>

        <view class="popup-content" v-if="selectedDay">
          <!-- 日期 -->
          <view class="detail-section">
            <view class="section-title">
              {{ selectedDay.fullDate }}
            </view>
          </view>

          <!-- 排班信息 -->
          <view
            class="detail-section"
            v-if="selectedDay.hasSchedule && selectedDay.scheduleInfo"
          >
            <view class="detail-item">
              <text class="item-label">员工姓名</text>
              <text class="item-value">{{
                selectedDay.scheduleInfo.record.PersonName || "-"
              }}</text>
            </view>
            <view class="detail-item">
              <text class="item-label">员工编号</text>
              <text class="item-value">{{ currentUserStaffNo }}</text>
            </view>
            <view class="detail-item">
              <text class="item-label">班次</text>
              <text class="item-value">{{
                selectedDay.scheduleInfo.shiftGroupName
              }}</text>
            </view>
            <view class="detail-item">
              <text class="item-label">工作时间</text>
              <text class="item-value">{{
                selectedDay.scheduleInfo.timeRange || "-"
              }}</text>
            </view>

            <!-- 实际打卡时间 -->
            <view class="detail-subsection">
              <view class="subsection-title">实际打卡时间</view>
              <view
                v-if="
                  !selectedDay.scheduleInfo.record.StartTime &&
                  !selectedDay.scheduleInfo.record.EndTime
                "
                class="no-punch-tip"
              >
                暂无打卡记录
              </view>
              <view v-else>
                <view class="detail-item">
                  <text class="item-label">上班打卡</text>
                  <text class="item-value">{{
                    selectedDay.scheduleInfo.record.StartTime || "-"
                  }}</text>
                </view>
                <view class="detail-item">
                  <text class="item-label">下班打卡</text>
                  <text class="item-value">{{
                    selectedDay.scheduleInfo.record.EndTime || "-"
                  }}</text>
                </view>
              </view>
            </view>

            <view class="detail-item">
              <text class="item-label">班次状态</text>
              <text class="item-value">{{
                selectedDay.scheduleInfo.record.ShiftType || "-"
              }}</text>
            </view>
            <view class="detail-item">
              <text class="item-label">考勤结果</text>
              <text
                class="item-value"
                :class="
                  getAttendanceResultClass(
                    selectedDay.scheduleInfo.attendanceResult,
                  )
                "
              >
                {{ selectedDay.scheduleInfo.attendanceResult || "未计算" }}
              </text>
            </view>
          </view>

          <!-- 无排班提示 -->
          <view class="detail-section" v-else>
            <view class="no-schedule-tip">
              <uni-icons type="info" size="24" color="#c0c4cc"></uni-icons>
              <text>该日期无排班信息</text>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
  </XenPageLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import CalendarView from "./components/CalendarView.vue";
import SysAttendanceRecordApi from "./api/index";
import type { IAttendanceRecord } from "./api/interface";

// API 实例
const api = SysAttendanceRecordApi();

// 排班记录数据
const scheduleRecords = ref<IAttendanceRecord[]>([]);

// 选中的日期
const selectedDay = ref<any>(null);

// 详情弹窗引用
const detailPopup = ref<any>(null);

// 当前年月
const currentYear = ref<number>(new Date().getFullYear());
const currentMonth = ref<number>(new Date().getMonth() + 1);

// 获取当前用户信息
const getCurrentUserInfo = () => {
  return uni.getStorageSync("userInfo");
};

// 获取当前用户工号
const currentUserStaffNo = computed(() => {
  const userInfo = getCurrentUserInfo();
  return userInfo?.ITCode || "-";
});

// 加载排班数据
const loadScheduleData = async (year: number, month: number) => {
  const userInfo = getCurrentUserInfo();
  console.log("获取到的用户信息:", userInfo);

  if (!userInfo || !userInfo.ITCode) {
    console.warn("无法获取用户工号(ITCode)");
    uni.showToast({
      title: "无法获取用户信息",
      icon: "none",
    });
    return;
  }

  try {
    uni.showLoading({ title: "加载中..." });

    // 计算月份的开始和结束日期
    const startDate = `${year}-${String(month).padStart(2, "0")}-01`;
    const lastDay = new Date(year, month, 0).getDate();
    const endDate = `${year}-${String(month).padStart(2, "0")}-${String(
      lastDay,
    ).padStart(2, "0")}`;

    console.log("查询参数:", {
      StaffNo: userInfo.ITCode,
      ShiftDate: [startDate, endDate],
    });

    const response = await api.searchByPerson({
      StaffNo: userInfo.ITCode,
      Page: 1,
      Limit: 100,
      IsPlainText: true,
      IsEmunToString: true,
      ShiftDate: [startDate, endDate],
    });

    console.log("API返回数据:", response);

    if (
      response &&
      response.Data &&
      response.Data.length > 0 &&
      response.Data[0].Records
    ) {
      console.log("原始记录数:", response.Data[0].Records.length);
      // 不过滤"未计算"的记录，全部显示
      scheduleRecords.value = response.Data[0].Records;
      console.log("最终记录数:", scheduleRecords.value.length);
    } else {
      console.log("没有找到排班记录");
      scheduleRecords.value = [];
    }

    uni.hideLoading();
  } catch (error) {
    console.error("加载排班数据失败:", error);
    uni.hideLoading();
    uni.showToast({
      title: "加载失败，请重试",
      icon: "none",
    });
  }
};

// 月份切换
const handleMonthChange = (year: number, month: number) => {
  currentYear.value = year;
  currentMonth.value = month;
  loadScheduleData(year, month);
};

// 日期点击
const handleDayClick = (day: any) => {
  selectedDay.value = day;
  detailPopup.value?.open();
};

// 关闭详情弹窗
const closeDetailPopup = () => {
  detailPopup.value?.close();
};

// 获取考勤结果样式类
const getAttendanceResultClass = (result: string) => {
  // 正常、请假、休假 - 绿色
  if (result === "正常" || result === "请假" || result === "休假") {
    return "success";
  }
  // 迟到、早退、迟到且早退 - 橙色
  else if (result === "迟到" || result === "早退" || result === "迟到且早退") {
    return "warning";
  }
  // 旷工、缺卡、缺勤、出勤 - 红色
  else if (
    result === "旷工" ||
    result === "缺卡" ||
    result === "缺勤" ||
    result === "出勤"
  ) {
    return "error";
  }
  // 未计算等其他状态 - 默认
  return "";
};

// 格式化分钟为小时
const formatMinutesToHours = (minutes: number) => {
  const hours = Math.floor(minutes / 60);
  const mins = minutes % 60;
  return `${hours} 小时 ${mins} 分钟`;
};

// 页面加载
onMounted(() => {
  loadScheduleData(currentYear.value, currentMonth.value);
});
</script>

<style lang="scss" scoped>
.detail-popup {
  background: #ffffff;
  border-radius: 16px 16px 0 0;
  max-height: 70vh;
  overflow: hidden;

  .popup-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px;
    border-bottom: 1px solid #e8eaed;

    .popup-title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }

    .popup-close {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      background: #f5f7fa;
      transition: all 0.3s ease;

      &:active {
        background: #e8eaed;
      }
    }
  }

  .popup-content {
    padding: 20px;
    max-height: calc(70vh - 60px);
    overflow-y: auto;

    .detail-section {
      margin-bottom: 24px;

      &:last-child {
        margin-bottom: 0;
      }

      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 2px solid #e8eaed;
      }

      .detail-subsection {
        background: #f9fafb;
        border-radius: 8px;
        padding: 12px;
        margin: 12px 0;

        .subsection-title {
          font-size: 13px;
          font-weight: 600;
          color: #606266;
          margin-bottom: 8px;
        }

        .no-punch-tip {
          text-align: center;
          padding: 16px 0;
          color: #c0c4cc;
          font-size: 13px;
        }

        .detail-item {
          border-bottom: none;
          padding: 8px 0;

          &:last-child {
            padding-bottom: 0;
          }
        }
      }

      .detail-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .item-label {
          font-size: 14px;
          color: #909399;
        }

        .item-value {
          font-size: 14px;
          color: #303133;
          font-weight: 500;

          &.success {
            color: #52c41a;
          }

          &.warning {
            color: #faad14;
          }

          &.error {
            color: #ff4d4f;
          }
        }
      }

      .no-schedule-tip {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 40px 20px;
        color: #c0c4cc;

        text {
          margin-top: 12px;
          font-size: 14px;
        }
      }
    }
  }
}
</style>
